import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:tapjoy_offerwall/tapjoy_offerwall.dart';

/// 轻量封装：Tapjoy SDK 连接与常用操作
class TapjoyService {
  TapjoyService._internal();
  static final TapjoyService instance = TapjoyService._internal();

  bool _connected = false;
  bool get isConnected => _connected;
  final Map<String, TJPlacement> _placements = <String, TJPlacement>{};

  /// 连接 Tapjoy
  /// [sdkKey] 来自 Tapjoy 控制台；[options] 为可选配置（日志、隐私、用户ID等）
  Future<bool> connect({
    required String sdkKey,
    Map<String, dynamic>? options,
    VoidCallback? onSuccess,
    void Function(int code, String? error)? onFailure,
    void Function(int code, String? warning)? onWarning,
  }) async {
    final Map<String, dynamic> opts = options ?? <String, dynamic>{};
    final completer = Completer<bool>();
    await Tapjoy.connect(
      sdkKey: sdkKey,
      options: opts,
      onConnectSuccess: () async {
        _connected = true;
        onSuccess?.call();
        if (!completer.isCompleted) completer.complete(true);
      },
      onConnectFailure: (int code, String? error) async {
        _connected = false;
        debugPrint('[Tapjoy] connect failure code=$code error=$error');
        onFailure?.call(code, error);
        if (!completer.isCompleted) completer.complete(false);
      },
      onConnectWarning: (int code, String? warning) async {
        debugPrint('[Tapjoy] connect warning code=$code warning=$warning');
        onWarning?.call(code, warning);
      },
    );
    // 等待成功或失败回调，确保连接状态明确
    return completer.future;
  }

  /// 构造一个常用的默认选项集
  Map<String, dynamic> buildDefaultOptions({
    bool enableLogging = true,
    bool userConsent = false,
    bool isBelowConsentAge = false,
    String? userId,
  }) {
    final Map<String, dynamic> m = <String, dynamic>{
      'enableLogging': enableLogging,
      'userConsent': userConsent,
      'isBelowConsentAge': isBelowConsentAge,
    };
    if (userId != null && userId.isNotEmpty) {
      m['userId'] = userId;
    }
    return m;
  }

  /// 设置用户ID（如插件支持）
  Future<void> setUserId(String userId) async {
    try {
      await Tapjoy.setUserID(userId: userId);
    } catch (e) {
      debugPrint('[Tapjoy] setUserID error: $e');
    }
  }

  /// 动态设置隐私合规（如插件支持），否则请在 options 中传入
  Future<void> setConsent({
    required bool userConsent,
    required bool isBelowConsentAge,
  }) async {
    try {
      debugPrint('[Tapjoy] setConsent userConsent=$userConsent isBelowConsentAge=$isBelowConsentAge');
    } catch (e) {
      debugPrint('[Tapjoy] setConsent error: $e');
    }
  }

  /// 请求广告位（Placements）
  Future<void> requestPlacement(String placement) async {
    try {
      debugPrint('[Tapjoy] requestPlacement $placement');
    } catch (e) {
      debugPrint('[Tapjoy] requestPlacement error: $e');
    }
  }

  /// 展示广告位（Placements）
  Future<void> showPlacement(String placement) async {
    try {
      debugPrint('[Tapjoy] showPlacement $placement');
    } catch (e) {
      debugPrint('[Tapjoy] showPlacement error: $e');
    }
  }

  /// 展示任务墙（Offerwall）
  Future<void> showOfferwall({
    required String placementName,
    TJEntryPoint? entryPoint,
  }) async {
    try {
      // 按文档：先获取 TJPlacement，再 requestContent，待就绪展示
      final TJPlacement placement = await ensurePlacement(
        placementName: placementName,
        entryPoint: entryPoint,
      );
      bool ready = await placement.isContentReady();
      if (!ready) {
        // 若未就绪，先请求内容并短暂轮询等待就绪，提高首次点击成功率
        placement.requestContent();
        const int maxTries = 10; // 最长等待约5秒
        for (int i = 0; i < maxTries; i++) {
          await Future.delayed(const Duration(milliseconds: 500));
          try {
            ready = await placement.isContentReady();
          } catch (_) {
            ready = false;
          }
          if (ready) break;
        }
      }
      if (ready) {
        placement.showContent();
      } else {
        debugPrint('[Tapjoy] Offerwall not ready after wait: $placementName');
      }
    } catch (e) {
      debugPrint('[Tapjoy] showOfferwall error: $e');
    }
  }

  /// 获取或创建一个 Placement，并可选设置入口点
  Future<TJPlacement> ensurePlacement({
    required String placementName,
    TJEntryPoint? entryPoint,
  }) async {
    TJPlacement? p = _placements[placementName];
    if (p == null) {
      p = await TJPlacement.getPlacement(placementName: placementName);
      _placements[placementName] = p;
    }
    if (entryPoint != null) {
      try {
        p.setEntryPoint(entryPoint);
      } catch (_) {}
    }
    return p;
  }

  /// 主动请求内容（预缓存）
  Future<void> requestContent(String placementName) async {
    try {
      final p = await ensurePlacement(placementName: placementName);
      p.requestContent();
    } catch (e) {
      debugPrint('[Tapjoy] requestContent error: $e');
    }
  }

  /// 检查并展示（若未就绪则先请求）
  Future<void> showIfReadyOrRequest(String placementName) async {
    try {
      final p = await ensurePlacement(placementName: placementName);
      if (await p.isContentReady()) {
        p.showContent();
      } else {
        p.requestContent();
      }
    } catch (e) {
      debugPrint('[Tapjoy] showIfReadyOrRequest error: $e');
    }
  }
}